import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link ,browserHistory} from 'react-router';
import api from '../api';

import {message,Row,Col,Card,Input,Button,Tabs,Table,Popconfirm} from 'antd';
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import LoanDetail from './LoanDetail';
import {bind_change} from '../common/State';
const TabPane = Tabs.TabPane;

//导入常量
import {INVEST_STATUS,RAISE_STATUS,REPAY_STATUS} from '../constants/index';

export default class RaiseLoanDetail extends React.Component {
  constructor(props, context){
      super(props, context);
      let {id,tab='invest'} = this.props.location.query||{};
      this.state={
        id,
        stopLoading:false,
        loan:{
          data:null
        },
        investRecord:{
          list:[],
          page:1,
          total:1,
          size:10,
          loading:true
        },
        refundPlan:{
          list:[],
          page:1,
          total:1,
          size:10,
          loading:true
        },
        tab
      };
  }

  componentWillMount(){
    let {tab} = this.state;
    if(tab!='loan'){
      this.fetchLoan()
    }
    this.doGet(tab)
  }

  componentWillReceiveProps(nextProps){
    // let {tab} = nextProps.location.query||{};
    // if(tab!='loan'){
    //   this.fetchLoan()
    // }
    // this.doGet(tab)
  }

  componentDidUpdate() {
    
  }

  async doGet(tab){
    let {loan,investRecord,refundPlan} = this.state;
    switch(tab){
      case "loan":
        this.fetchLoan();
        break;
      case "invest":
        investRecord.loading = true;
        this.setState({tab,investRecord})
        this.fetchInvestRecord();
        break;
      case "plan":
        refundPlan.loading = true;
        this.setState({tab,refundPlan})
        this.fetchPlanRecord();
        break;
    }
  }

  //查询项目基本信息
  async fetchLoan(){
    let {loan,id} = this.state;
    let result = await api('/loan/raise/detail' ,{id});
    loan.loading = false;
    if(result.cd!=0){
      message.error(result.msg);
      this.setState({
        loan,
        stopLoading:false
      })
      return
    }
    loan.data = result.data;
    this.setState({loan});
  }

  //查询投资记录
  async fetchInvestRecord(page=1){

    let {investRecord,id} = this.state;

    let result = await api('/loan/raise/invest',{id,page});

    investRecord.loading = false
    if(result.cd!=0){
      message.error(result.msg);
      this.setState({
        investRecord
      })
      return;
    }
    investRecord.total = result.total;
    investRecord.page = page;
    investRecord.list = result.data;

    this.setState({
        investRecord
    })
  }

  //查询还款计划
  async fetchPlanRecord(page){
    let {refundPlan,id} = this.state;

    let result = await api('/loan/raise/repayplan',{id});
    refundPlan.loading = false
    if(result.cd!=0){
      message.error(result.msg);
      this.setState({
        refundPlan
      })
      return;
    }
    refundPlan.total = result.total;
    refundPlan.page = page;
    refundPlan.list = result.data;

    this.setState({
        refundPlan
    })
  }

  //投资记录翻页
  investPageTo({current:page,total,pageSize}){
    let {investRecord} = this.state;
    investRecord.loading = true;
    this.setState({investRecord});

    this.fetchInvestRecord(page)
  }

  //还款计划翻页
  planPageTo({current:page,total,pageSize}){
    let {refundPlan} = this.state;
    refundPlan.loading = true;
    this.setState({refundPlan});
    
    this.fetchPlanRecord(page)
  }

  //处理tab切换事件
  handleTabsChange(tab){
    this.setState({tab});
    this.doGet(tab);
  }

  //终止项目
  async handleStopLoan(){
    this.setState({stopLoading:true})
    let {id} = this.state;
    let result = await api('/loan/raise/stop',{id})
    if(result.cd!=0){
      message.error(result.msg)
      this.setState({stopLoading:false});
      return
    }
    message.success('操作成功')
    this.setState({stopLoading:false});
    this.fetchLoan();
  }
  //确认放款
  async confirm(){
    let {loan} = this.state;
    loan.data = loan.data||{};
    let result = await api('/loan/raise/confirm',{id:loan.data.id});
      if(result.cd!=0){
        message.error(result.msg);
        return
      }
    message.success('放款成功')
    this.fetchLoan();
  }
  //还款提醒
  async refundTips(){
    let {loan} = this.state;
    loan.data = loan.data||{};
    let result = await api('/loan/raise/repayTip',{phone:loan.data.borrower_phone,projectId:loan.data.id});
    if(result.cd!=0){
      message.error(result.msg);
      return
    }
    message.success('已提醒');
    this.fetchLoan();
  }
  
  

  //还款计划列表操作
  async handlePlanOption(record,key){
    let {refundPlan,id} = this.state;
    let result = null;
    if(key=='repay'){
      result = await api('/loan/raise/splitByAccount',{id,period:record.current_period});
    }
    // if(key=="tip"){
    //   result = await api('/loan/raise/repayTip',{id,period:record.current_period});
    // }
    if(result.cd!=0){
      message.error(result.msg);
      return
    }
    message.success('操作成功')
    refundPlan.loading = true;
    this.setState({refundPlan});
    this.fetchPlanRecord(refundPlan.page)
    this.fetchLoan();
  }


  render() {
    let {
      investRecord,
      refundPlan,
      loan,
      tab,
      id,
      stopLoading
    } = this.state;
    loan.data = loan.data||{};
    return (
        <div>
            <NavBar navs={[
              {title:'在筹项目管理',href:'/loan/raise/list'},
              {title:'在筹项目详情'}
            ]} />
            <ContentBody className='container'> 
              <div className='flex middle' >
                <label style={{fontSize:'14px',fontWeight:'blod'}}>项目状态:</label>
                <span 
                  style={{fontSize:'14px',fontWeight:'blod'}} 
                  className='marginL10 marginR10'
                >
                  {RAISE_STATUS[loan.data.status]}
                </span>
                {loan.data.status==3?
                  <Button 
                    type="primary"
                    loading={stopLoading}
                    onClick={this.handleStopLoan.bind(this)}
                  >
                  终止项目
                  </Button>
                  :loan.data.status==9||loan.data.status==7?
                  <Button 
                    type="primary"
                    loading={false}
                    onClick={this.confirm.bind(this)}
                  >
                  确认放款
                  </Button>
                  :loan.data.status==13||loan.data.status==16?
                  <Button 
                    type="primary"
                    loading={stopLoading}
                    onClick={this.refundTips.bind(this)}
                  >
                  还款提醒
                  </Button>
                  :loan.data.status == 17?
                  <Button 
                    type="primary"
                    loading={stopLoading}
                    onClick={() => {
                      this.handleTabsChange('plan')
                    }}
                  >
                  还款分账
                  </Button>
                  :null
                }
                
              </div>
              <div className='height20'></div>
              <div className='search-panel'>
                  <Row gutter={16}>
                    <Col span={8}>
                      <label>项目编号:</label>
                      <span className='marginL10'>{id}</span>
                    </Col>
                    <Col span={8}>
                      <label>借款人姓名:</label>
                      <span className='marginL10'>{loan.data.borrower_name}</span>
                    </Col>
                    <Col span={8}>
                      <label>借款人手机号:</label>
                      <span className='marginL10'>{loan.data.borrower_phone}</span>
                    </Col>
                  </Row>
              </div>
              <Tabs defaultActiveKey={tab} activeKey={tab} onTabClick={this.handleTabsChange.bind(this)}>
                <TabPane tab={"项目基本信息"} key="loan">
                  <LoanDetail 
                    data={loan.data}
                  />
                </TabPane>
                <TabPane tab="投资记录" key="invest">
                  <Table 
                    bordered
                    columns={this.getInvestRecordColumns()} 
                    simple 
                    dataSource={investRecord.list}
                    pagination={{
                      current:investRecord.page,
                      total:investRecord.total,
                      pageSize:investRecord.size,
                      showQuickJumper : true
                    }}
                    loading={investRecord.loading}
                    onChange={this.investPageTo.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                  />
                </TabPane>
                <TabPane tab="还款计划" key="plan">
                  <Table 
                    bordered
                    columns={this.getRefundPlanColumns()} 
                    simple 
                    dataSource={refundPlan.list}
                    pagination={false}
                    loading={refundPlan.loading}
                    onChange={this.planPageTo.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                  />
                </TabPane>
              </Tabs>
            </ContentBody>
        </div>
    )
  }

  //投资记录显示字段
  getInvestRecordColumns(){
    let columns = [
          {
            title: '投资ID',
            dataIndex: 'investId',
            key: 'investId',
          }, {
            title: '投资人昵称',
            dataIndex: 'nickname',
            key: 'nickname',
            
          }, {
            title: '投资人手机号',
            dataIndex: 'phone',
            key: 'phone'
          },{
            title: '投资额',
            dataIndex: 'investment',
            key: 'investment',
          }, {
            title: '项目利息',
            dataIndex: 'interest',
            key: 'interest'
          },{
            title: '投资创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt'
          },{
            title: '支付状态',
            dataIndex: 'status',
            key: 'status',
            render:(status)=>{
              return INVEST_STATUS[status];
            }
          }
      ];

      return columns
  }

  //还款计划显示字段
  getRefundPlanColumns(){
    let columns = [
          {
            title: '还款期数',
            dataIndex: 'current_period',
            key: 'current_period',
          }, {
            title: '还款额',
            dataIndex: 'repay_amount',
            key: 'repay_amount',
            
          }, {
            title: '剩余金额',
            dataIndex: 'remain_amount',
            key: 'remain_amount'
          },{
            title: '还款时间',
            dataIndex: 'plan_repay_at',
            key: 'plan_repay_at',
          }, {
            title: '还款状态',
            dataIndex: 'status',
            key: 'status',
            render:(status)=>{
              return REPAY_STATUS[status]
            }
          },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:100,
              render: (record) =>{
                if(record.status==3){
                  return (
                    <a href='javascript:void 0;' onClick={this.refundTips.bind(this)}>提醒用户</a>
                  )
                }
                if(record.status==2&&record.split_status==0){
                  return (
                    <Popconfirm title="确定还款分账?" onConfirm={this.handlePlanOption.bind(this,record,'repay')} >
                      <a href='javascript:void 0;' >还款分账</a>
                    </Popconfirm>
                  )
                }
                
              } 
            }
      ];

      return columns
  }
}
RaiseLoanDetail.contextTypes= { router: React.PropTypes.object.isRequired};

